<?php
require_once("functions.php");
require_once("database.php");

session_start();

if($_GET and isset($_GET['id']) and is_numeric($_GET['id'])){

  //ordering
  $ordering = "ORDER BY date DESC";
  if(isset($_GET['ordering'])){
    if($_GET['ordering'] == 'priceup'){
      $ordering = "ORDER BY price ASC";
    }
    else if($_GET['ordering'] == 'pricedown'){
      $ordering = "ORDER BY price DESC";
    }
    else if($_GET['ordering'] == 'locationup'){
      $ordering = "ORDER BY location ASC";
    }
    else if($_GET['ordering'] == 'locationdown'){
      $ordering = "ORDER BY location DESC";
    }
    else if($_GET['ordering'] == 'rooms0'){
      $ordering = "AND bedrooms = 0";
    }
    else if($_GET['ordering'] == 'rooms1'){
      $ordering = "AND bedrooms = 1";
    }
    else if($_GET['ordering'] == 'rooms2'){
      $ordering = "AND bedrooms = 2"; 
    }
    else if($_GET['ordering'] == 'rooms3'){
      $ordering = "AND bedrooms = 3";
    }
    else if($_GET['ordering'] == 'rooms4'){
      $ordering = "AND bedrooms = 4";
    }
    else if($_GET['ordering'] == 'roomsgt4'){
      $ordering = "AND bedrooms > 4";
    }
  }

  // Get apartment info
  $safe_id = sql_escape($_GET['id']);
  $apartments = query_select("
    SELECT *
    FROM apartment
    WHERE city_id = " . $safe_id . "
    AND date >= " . mktime(0,0,0) . "
    " . $ordering
  );
  
  // Get city info
  $city = query_select("
    SELECT name, url
    FROM city
    WHERE id = " . $safe_id
  );
  
  $today = time();
  $days = 14;
  $day_min = $today - (($days) * 60 * 60 * 24);
  $day_max = $today;
  $sql = "
      SELECT ROUND(AVG(price), 2) AS avg_price
      FROM apartment
      WHERE date >= " . $day_min . "
      AND date < " . $day_max . "
      AND city_id = " . sql_escape($_GET['id']);

  $aprices = query_select($sql);
  $average_price = $aprices[0]['avg_price'];
  
  if(count($city) == 0){
    // Error, send back to index
    header('location: index.php');
    exit;
  }
  $city_name = ucwords($city[0]['name']);
  $city_url = $city[0]['url'];
  
  $my_city = Null;
  if(isset($_SESSION['user'])){
    // Get user info
    $userinfo = query_select("
      SELECT default_city
      FROM user
      WHERE id = " . $_SESSION['user']
    );

    $my_city = $userinfo[0]['default_city'];
  }
  
  $all_apartments = query_select("
    SELECT *
    FROM apartment
    WHERE city_id = " . $safe_id . "
    AND date >= " . mktime(0,0,0)
  );
  
  $all_prices = array();
  foreach($all_apartments as $aj){
    array_push($all_prices,$aj['price']);
  }

}
else {
  header('location: index.php');
  exit;
}

?>

<?php $onload_function = "initialize();" ?>
<?php require_once("header.php"); ?>
<div id = "citycenter">
	<div id = "cityleftcol">
		<div id = "citybigbox">
				<div id = "citycurved"></div>
				<div id = "citybox">
					<div class="statistics">
						<p class ="citytitle"><a class = "citytitle" href="<?php echo $city_url ?>"><?php echo $city_name ?></a></p>
						<ul>
							<li>Average Price: $<?php echo $average_price; ?></li>
							<li>Maximum Price: $<?php echo max($all_prices); ?>.00</li>
							<li>Minimum Price: $<?php echo min($all_prices); ?>.00</li>
						</ul>
					</div>
				</div>
		</div>
		
		<div id="map_canvas" style="width: 444px; height: 300px; margin-top: 10px"></div>
		
	</div>



<div id = "cityrightcol">

<?php


if(isset($_SESSION['user']) and $safe_id != $my_city){
  echo '<div id="defaultcity">';
  echo '<a href="setdefault.php?id='. $safe_id.'">Make default City</a>';
  echo '</div>';
}
else if($safe_id == $my_city){
  echo '<div id="defaultcity">';
  echo 'This is your default city!';
  echo '</div>';
}

?>
	<img src="chart.php?id=<?php echo $safe_id ?>"/>
</div>

<div class="clear"> <!-- keeps floats within parent container --></div> 
</div>


<div id = "citiesbox">
		<div id = "citiescurved"></div>
		<div id = "cities">
<div id="apartments">
<table>
  <tr>
    <td width="10%"><b>Price</b> <a href="city.php?id=<?php echo $safe_id ?>&ordering=priceup"><img src = "./layout/uparrow.png" /></a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=pricedown"><img src = "./layout/downarrow.png" /></a></td>
    <td width="25%"><b>Location</b> <a href="city.php?id=<?php echo $safe_id ?>&ordering=locationup"><img src = "./layout/uparrow.png" /></a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=locationdown"><img src = "./layout/downarrow.png" /></a></td>
    <td width="23%"><b>Bedrooms</b> <a href="city.php?id=<?php echo $safe_id ?>&ordering=rooms0">&lt;1</a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=rooms1">1</a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=rooms2">2</a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=rooms3">3</a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=rooms4">4</a> <a href="city.php?id=<?php echo $safe_id ?>&ordering=roomsgt4">&gt;4</a><a href="city.php?id=<?php echo $safe_id ?>"> All</a></td>
    <td width="10%"><b>Date Added</b></td>
    <td width="27%"><b>Description</b></td>
    <?php
      if(user_admin()){
        echo '<td></td>';
      }
      ?>
  </tr>
<?php
foreach($apartments as $apartment){
    echo '<tr>';
    
    echo '<td>$' . $apartment['price'] . '</td>';
    echo '<td>' . $apartment['location'] . '</td>';
    echo '<td>' . $apartment['bedrooms'] . ' bedrooms</td>';
    echo '<td>' . date("D M j",$apartment['date']) . '</td>';
    echo '<td><a href="'.$apartment['url'].'">' . $apartment['title'] . '</a></td>';
    if(user_admin()){
      echo '<td>';
      echo '<a href="admin/dodeleteappt.php?id=' . $apartment['id'] . '&city=' . $safe_id . '"><img src ="./layout/xbutton.png"/></a>';
      echo '</td>';
    }
    
    echo '</tr>';
}
?>
</table>
</div>
</div>
</div>

<form>
	<input type="hidden" id="addr" value="<?php echo $city_name; ?>" />
	<input type="hidden" id="cost" value="<?php echo $average_price; ?>"/>
</form>

<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;sensor=false&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA" type="text/javascript"></script>
    <script type="text/javascript">
    var map;
    var geocoder;

    function initialize() {
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(34, 0), 2);
      geocoder = new GClientGeocoder();
      var address = document.getElementById("addr").value;
	  var cost = "<br>Average Cost of Living: $" + document.getElementById("cost").value;
     //document.write(address + ", lol<br>");
      showAddress(address, cost);
    }
    
    
    function showAddress(address, desc) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
              map.addOverlay(marker);
          GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml("<b>" + address + "</b>" + desc);
          });
              return point;
            }
          }
        );
        return false;
      }
    }

    
    // showLocation() geocodes the address entered 
    // and adds a marker to the map at that location.
    </script>

<?php require_once("footer.php"); ?>
